//
//  ZFPlayerControlView.m
//
// Copyright (c) 2016年 任子丰 ( http://github.com/renzifeng )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#import "ZFPlayerControlView.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import "UIView+CustomControlView.h"
#import "MMMaterialDesignSpinner.h"
#import "DMBarrageDataPrv.h"
#import "DMPlayerCommonHeader.h"
#import "DMBarrageIFieldView.h"
#import "ZFPlayerErrorView.h"
#import "ZFContinuePlayView.h"
#import "ZFPlayerNetWorkReachability.h"
#import "DMPlayerCommonHeader.h"
#import <Masonry/Masonry.h>
#import "ASValueTrackingSlider.h"
#import "DMPlayer.h"
#define DMKTOPHEIGHT              60.0
#define DMKSMALL_TOPHEIGHT        45.0

#define DMKSMALL_BOTTONHEIGHT     46.0
#define DMKBOTTOMHEIGHT           56.0

#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wdeprecated-declarations"

static const CGFloat ZFPlayerAnimationTimeInterval             = 7.0f;
static const CGFloat ZFPlayerControlBarAutoFadeOutTimeInterval = 0.35f;

@interface ZFPlayerControlView () <UIGestureRecognizerDelegate,BarrageRendererDelegate>

@property (strong, nonatomic) ZFPlayerModel *playerModel;
/** 标题 */
@property (nonatomic, strong) UILabel                 *titleLabel;
/** 开始播放按钮 */
@property (nonatomic, strong) UIButton                *startBtn;
/** 当前播放时长label */
@property (nonatomic, strong) UILabel                 *currentTimeLabel;
/** 视频总时长label */
@property (nonatomic, strong) UILabel                 *totalTimeLabel;
/** 缓冲进度条 */
@property (nonatomic, strong) UIProgressView          *progressView;
/** 滑杆 */
@property (nonatomic, strong) ASValueTrackingSlider   *videoSlider;
/** 全屏按钮 */
@property (nonatomic, strong) UIButton                *fullScreenBtn;
/** 锁定屏幕方向按钮 */
@property (nonatomic, strong) UIButton                *lockBtn;
/** 系统菊花 */
@property (nonatomic, strong) MMMaterialDesignSpinner *activity;
/** 返回按钮*/
@property (nonatomic, strong) UIButton                *backBtn;
/** 关闭按钮*/
@property (nonatomic, strong) UIButton                *closeBtn;
/** 重播按钮 */
@property (nonatomic, strong) UIButton                *repeatBtn;
/** bottomView*/
@property (nonatomic, strong) UIImageView             *bottomImageView;
/** topView */
@property (nonatomic, strong) UIImageView             *topImageView;
/** 缓存按钮 */
@property (nonatomic, strong) UIButton                *downLoadBtn;
/** 切换分辨率按钮 */
@property (nonatomic, strong) UIButton                *resolutionBtn;
/** 分辨率的View */
@property (nonatomic, strong) UIView                  *resolutionView;
/** 播放按钮 */
@property (nonatomic, strong) UIButton                *playeBtn;
/** 加载失败按钮 */
@property (nonatomic, strong) ZFPlayerErrorView                *errorView;
/** 非 Wifi 下显示 */
@property (strong, nonatomic) ZFContinuePlayView *continuePlayView;
@property (strong, nonatomic) ZFPlayerNetWorkReachability *reachability;
/** 快进快退View*/
@property (nonatomic, strong) UIView                  *fastView;
/** 快进快退进度progress*/
@property (nonatomic, strong) UIProgressView          *fastProgressView;
/** 快进快退时间*/
@property (nonatomic, strong) UILabel                 *fastTimeLabel;
/** 快进快退ImageView*/
@property (nonatomic, strong) UIImageView             *fastImageView;
/** 当前选中的分辨率btn按钮 */
@property (nonatomic, weak  ) UIButton                *resoultionCurrentBtn;
/** 占位图 */
@property (nonatomic, strong) UIImageView             *placeholderImageView;
/** 控制层消失时候在底部显示的播放进度progress */
@property (nonatomic, strong) UIProgressView          *bottomProgressView;
/** 分辨率的名称 */
@property (nonatomic, strong) NSArray                 *resolutionArray;

/** 显示控制层 */
@property (nonatomic, assign, getter=isShowing) BOOL  showing;
/** 小屏播放 */
@property (nonatomic, assign, getter=isShrink ) BOOL  shrink;
/** 在cell上播放 */
@property (nonatomic, assign, getter=isCellVideo)BOOL cellVideo;
/** 是否拖拽slider控制播放进度 */
@property (nonatomic, assign, getter=isDragged) BOOL  dragged;
/** 是否播放结束 */
@property (nonatomic, assign, getter=isPlayEnd) BOOL  playeEnd;
/** 是否全屏播放 */
@property (nonatomic, assign,getter=isFullScreen)BOOL fullScreen;

/** 弹幕 */
@property (strong, nonatomic) BRBarrageRenderer *barrageRender;
@property (strong, nonatomic) UIButton *barrageSwitchBtn;
@property (strong, nonatomic) UIButton *barrageSendBtn;
@property (assign, nonatomic) NSTimeInterval currentPlayTime; /// 弹幕使用
@end

@implementation ZFPlayerControlView

- (instancetype)init {
	self = [super init];
	if (self) {
		[self addSubview:self.barrageRender.view];
		[self addSubview:self.placeholderImageView];
		[self addSubview:self.topImageView];
		[self addSubview:self.bottomImageView];
		[self.bottomImageView addSubview:self.startBtn];
		[self.bottomImageView addSubview:self.currentTimeLabel];
		[self.bottomImageView addSubview:self.progressView];
		[self.bottomImageView addSubview:self.videoSlider];
		[self.bottomImageView addSubview:self.fullScreenBtn];
		[self.bottomImageView addSubview:self.totalTimeLabel];
		[self.bottomImageView addSubview:self.barrageSwitchBtn];
		[self.bottomImageView addSubview:self.barrageSendBtn];
		
		
		[self.topImageView addSubview:self.downLoadBtn];
		[self addSubview:self.lockBtn];
		[self.topImageView addSubview:self.backBtn];
		[self addSubview:self.activity];
		[self addSubview:self.repeatBtn];
		[self addSubview:self.playeBtn];
		[self addSubview:self.errorView];
		[self addSubview:self.continuePlayView];
		
		[self addSubview:self.fastView];
		[self.fastView addSubview:self.fastImageView];
		[self.fastView addSubview:self.fastTimeLabel];
		[self.fastView addSubview:self.fastProgressView];
		
		[self.topImageView addSubview:self.resolutionBtn];
		[self.topImageView addSubview:self.titleLabel];
		[self addSubview:self.closeBtn];
		[self addSubview:self.bottomProgressView];
		
		// 添加子控件的约束
		[self makeSubViewsConstraints];
		
		self.downLoadBtn.hidden     = YES;
		self.resolutionBtn.hidden   = YES;
		self.fullScreen = NO;
		// 初始化时重置controlView
		[self zf_playerResetControlView];
		// app退到后台
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidEnterBackground) name:UIApplicationWillResignActiveNotification object:nil];
		// app进入前台
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidEnterPlayground) name:UIApplicationDidBecomeActiveNotification object:nil];
		
		[self listeningRotating];
	}
	return self;
}

- (void)dealloc {
	NSLog(@"player Control view Dealloc ");
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	[[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
	[self.reachability stopNotifier];
	self.reachability = nil;
}

- (void)makeSubViewsConstraints {
	
	[self.barrageRender.view mas_makeConstraints:^(MASConstraintMaker *make) {
		make.edges.equalTo(self);
	}];
	
	[self.placeholderImageView mas_makeConstraints:^(MASConstraintMaker *make) {
		make.edges.mas_equalTo(UIEdgeInsetsZero);
	}];
	
	[self.closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
		make.trailing.equalTo(self.mas_trailing).offset(7);
		make.top.equalTo(self.mas_top).offset(-7);
		make.width.height.mas_equalTo(20);
	}];
	
	if (self.isFullScreen) {
		[self makeFullScreenTopView];
	} else {
		[self makeSmallScreenTopView];
	}
	
	[self.downLoadBtn mas_makeConstraints:^(MASConstraintMaker *make) {
		make.width.mas_equalTo(40);
		make.height.mas_equalTo(49);
		make.trailing.equalTo(self.topImageView.mas_trailing).offset(-10);
		make.centerY.equalTo(self.backBtn.mas_centerY);
	}];
	
	[self.resolutionBtn mas_makeConstraints:^(MASConstraintMaker *make) {
		make.width.mas_equalTo(40);
		make.height.mas_equalTo(25);
		make.trailing.equalTo(self.downLoadBtn.mas_leading).offset(-10);
		make.centerY.equalTo(self.backBtn.mas_centerY);
	}];
	
	[self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
		make.leading.equalTo(self.backBtn.mas_trailing).offset(5);
		make.centerY.equalTo(self.backBtn.mas_centerY);
		make.trailing.equalTo(self.resolutionBtn.mas_leading).offset(-10);
	}];
	
	[self.bottomImageView mas_makeConstraints:^(MASConstraintMaker *make) {
		make.leading.bottom.trailing.mas_equalTo(0);
		make.height.mas_equalTo(50);
	}];
	
	if (self.isFullScreen) {
		[self makeFullScreenBootomView];
	} else {
		[self makeSmallScreenBootomView];
	}
	
	self.lockBtn.hidden = YES;
	[self.lockBtn mas_makeConstraints:^(MASConstraintMaker *make) {
		make.leading.equalTo(self.mas_leading).offset(15);
		make.centerY.equalTo(self.mas_centerY);
		make.width.height.mas_equalTo(32);
	}];
	
	[self.repeatBtn mas_makeConstraints:^(MASConstraintMaker *make) {
		make.center.equalTo(self);
	}];
	
	[self.playeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
		make.width.height.mas_equalTo(50);
		make.center.equalTo(self);
	}];
	
	[self.activity mas_makeConstraints:^(MASConstraintMaker *make) {
		make.center.equalTo(self);
		make.width.with.height.mas_equalTo(45);
	}];
	
	[self.errorView mas_makeConstraints:^(MASConstraintMaker *make) {
		make.edges.mas_equalTo(UIEdgeInsetsZero);
	}];
	[self.continuePlayView mas_makeConstraints:^(MASConstraintMaker *make) {
		make.edges.mas_equalTo(UIEdgeInsetsZero);
	}];
	
	[self.fastView mas_makeConstraints:^(MASConstraintMaker *make) {
		make.width.mas_equalTo(125);
		make.height.mas_equalTo(80);
		make.center.equalTo(self);
	}];
	
	[self.fastImageView mas_makeConstraints:^(MASConstraintMaker *make) {
		make.width.mas_offset(32);
		make.height.mas_offset(32);
		make.top.mas_equalTo(5);
		make.centerX.mas_equalTo(self.fastView.mas_centerX);
	}];
	
	[self.fastTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
		make.leading.with.trailing.mas_equalTo(0);
		make.top.mas_equalTo(self.fastImageView.mas_bottom).offset(2);
	}];
	
	[self.fastProgressView mas_makeConstraints:^(MASConstraintMaker *make) {
		make.leading.mas_equalTo(12);
		make.trailing.mas_equalTo(-12);
		make.top.mas_equalTo(self.fastTimeLabel.mas_bottom).offset(10);
	}];
	
	[self.bottomProgressView mas_makeConstraints:^(MASConstraintMaker *make) {
		make.leading.bottom.trailing.mas_offset(0);
		make.height.mas_equalTo(1.5);
	}];
	
}

- (void)makeFullScreenBootomView
{
	
	[self.startBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
		make.leading.equalTo(self.bottomImageView.mas_leading).offset(10);
		make.bottom.equalTo(self.bottomImageView.mas_bottom).offset(0);
		make.width.height.mas_equalTo(50);
	}];
	
	[self.currentTimeLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
		make.leading.equalTo(self.startBtn.mas_trailing).offset(10);
		make.centerY.equalTo(self.startBtn.mas_centerY);
		make.width.mas_equalTo(43);
	}];
	
	[self.videoSlider mas_remakeConstraints:^(MASConstraintMaker *make) {
		make.leading.equalTo(self.currentTimeLabel.mas_trailing).offset(4);
		make.trailing.equalTo(self.totalTimeLabel.mas_leading).offset(-4);
		make.centerY.equalTo(self.currentTimeLabel.mas_centerY).offset(-1);
		make.height.mas_equalTo(30);
	}];
	
	[self.progressView mas_remakeConstraints:^(MASConstraintMaker *make) {
		make.leading.equalTo(self.currentTimeLabel.mas_trailing).offset(4);
		make.trailing.equalTo(self.totalTimeLabel.mas_leading).offset(-4);
		make.centerY.equalTo(self.startBtn.mas_centerY);
	}];
	
	[self.totalTimeLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
		make.centerY.equalTo(self.startBtn.mas_centerY);
		make.width.mas_equalTo(43);
	}];
	
	/// 添加弹幕的按钮
	[self.barrageSendBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
		make.leading.equalTo(self.totalTimeLabel.mas_trailing).offset(5);
		make.top.bottom.equalTo(self.bottomImageView);
		make.width.equalTo(self.barrageSendBtn.mas_height).multipliedBy(44.0 / 25.0);
	}];
	[self.barrageSwitchBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
		make.leading.equalTo(self.barrageSendBtn.mas_trailing).offset(5);
		make.trailing.equalTo(self.bottomImageView.mas_trailing);
		make.top.bottom.equalTo(self.bottomImageView);
		make.width.equalTo(self.barrageSwitchBtn.mas_height).multipliedBy(70.0 / 46.0);
	}];
	
	self.startBtn.hidden = NO;
	self.fullScreenBtn.hidden = YES;
	self.barrageSendBtn.hidden = NO;
	self.barrageSwitchBtn.hidden = NO;
}

- (void)makeSmallScreenBootomView
{
	[self.startBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
		make.leading.equalTo(self.bottomImageView.mas_leading).offset(5);
		make.bottom.equalTo(self.bottomImageView.mas_bottom).offset(-5);
		make.height.mas_equalTo(30);
		make.width.mas_equalTo(8); /// time 间距
	}];
	
	[self.currentTimeLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
		make.leading.equalTo(self.startBtn.mas_trailing).offset(3);
		make.centerY.equalTo(self.startBtn.mas_centerY);
		make.width.mas_equalTo(43);
	}];
	
	[self.videoSlider mas_remakeConstraints:^(MASConstraintMaker *make) {
		make.leading.equalTo(self.currentTimeLabel.mas_trailing).offset(4);
		make.trailing.equalTo(self.totalTimeLabel.mas_leading).offset(-4);
		make.centerY.equalTo(self.currentTimeLabel.mas_centerY).offset(-1);
		make.height.mas_equalTo(30);
	}];
	
	[self.progressView mas_remakeConstraints:^(MASConstraintMaker *make) {
		make.leading.equalTo(self.currentTimeLabel.mas_trailing).offset(4);
		make.trailing.equalTo(self.totalTimeLabel.mas_leading).offset(-4);
		make.centerY.equalTo(self.startBtn.mas_centerY);
	}];
	
	[self.totalTimeLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
		make.trailing.equalTo(self.fullScreenBtn.mas_leading).offset(-8);
		make.centerY.equalTo(self.startBtn.mas_centerY);
		make.width.mas_equalTo(43);
	}];
	
	[self.fullScreenBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
		make.width.height.mas_equalTo(30);
		make.trailing.equalTo(self.bottomImageView.mas_trailing).offset(-5);
		make.centerY.equalTo(self.startBtn.mas_centerY);
	}];
	
	/// 添加弹幕的按钮
	
	[self.barrageSendBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
//		make.width.height.mas_equalTo(0);
	}];
	[self.barrageSwitchBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
//		make.width.height.mas_equalTo(0);
	}];
	
	self.startBtn.hidden = YES;
	self.barrageSendBtn.hidden = YES;
	self.barrageSwitchBtn.hidden = YES;
	self.fullScreenBtn.hidden = NO;
}
- (void)makeSmallScreenTopView
{
	if (self.isCellVideo)
	{
		[self.backBtn setImage:nil forState:UIControlStateNormal];
	}
	[self.titleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
		make.leading.equalTo(self.backBtn.mas_trailing).offset(5);
		make.centerY.equalTo(self.backBtn.mas_centerY);
		make.trailing.lessThanOrEqualTo(self.resolutionBtn.mas_leading).offset(-10);
	}];
	
	[self.topImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
		make.leading.trailing.equalTo(self);
		make.top.equalTo(self.mas_top).offset(0);
		make.height.mas_equalTo(50);
	}];
	
	[self.backBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
		make.leading.equalTo(self.topImageView.mas_leading).offset(10);
		make.top.bottom.equalTo(self.topImageView).offset(0);
		make.width.equalTo(self.backBtn.mas_height).multipliedBy(0);
	}];
}
- (void)makeFullScreenTopView
{
	[self.backBtn setImage:ZFPlayerImage(@"ZFPlayer_back_full") forState:UIControlStateNormal];
	
	[self.titleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
		make.leading.equalTo(self.backBtn.mas_trailing).offset(5);
		make.centerY.equalTo(self.backBtn.mas_centerY);
		make.trailing.lessThanOrEqualTo(self.resolutionBtn.mas_leading).offset(-10);
		make.width.mas_lessThanOrEqualTo(ScreenWidth * 0.5);
	}];
	
	[self.topImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
		make.leading.trailing.equalTo(self);
		make.top.equalTo(self.mas_top).offset(0);
		make.height.mas_equalTo(70);
	}];
	
	[self.backBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
		make.leading.equalTo(self.topImageView.mas_leading).offset(10);
		make.top.equalTo(self.topImageView.mas_top).offset(20);
		make.bottom.equalTo(self.topImageView.mas_bottom).offset(0);
		make.width.equalTo(self.backBtn.mas_height).multipliedBy(1.0);
	}];
}
- (void)layoutSubviews {
	[super layoutSubviews];
	
	UIInterfaceOrientation currentOrientation = [UIApplication sharedApplication].statusBarOrientation;
	if (currentOrientation == UIDeviceOrientationPortrait) {
		[self setOrientationPortraitConstraint];
	} else {
		[self setOrientationLandscapeConstraint];
	}
}

#pragma mark - Action

/**
 *  点击切换分别率按钮
 */
- (void)changeResolution:(UIButton *)sender {
	sender.selected = YES;
	if (sender.isSelected) {
		sender.backgroundColor = RGBA(86, 143, 232, 1);
	} else {
		sender.backgroundColor = [UIColor clearColor];
	}
	self.resoultionCurrentBtn.selected = NO;
	self.resoultionCurrentBtn.backgroundColor = [UIColor clearColor];
	self.resoultionCurrentBtn = sender;
	// 隐藏分辨率View
	self.resolutionView.hidden  = YES;
	// 分辨率Btn改为normal状态
	self.resolutionBtn.selected = NO;
	// topImageView上的按钮的文字
	[self.resolutionBtn setTitle:sender.titleLabel.text forState:UIControlStateNormal];
	if ([self.delegate respondsToSelector:@selector(zf_controlView:resolutionAction:)]) {
		[self.delegate zf_controlView:self resolutionAction:sender];
	}
}

/**
 *  UISlider TapAction
 */
- (void)tapSliderAction:(UITapGestureRecognizer *)tap {
	if ([tap.view isKindOfClass:[UISlider class]]) {
		UISlider *slider = (UISlider *)tap.view;
		CGPoint point = [tap locationInView:slider];
		CGFloat length = slider.frame.size.width;
		// 视频跳转的value
		CGFloat tapValue = point.x / length;
		if ([self.delegate respondsToSelector:@selector(zf_controlView:progressSliderTap:)]) {
			[self.delegate zf_controlView:self progressSliderTap:tapValue];
		}
	}
}
// 不做处理，只是为了滑动slider其他地方不响应其他手势
- (void)panRecognizer:(UIPanGestureRecognizer *)sender {}

- (void)backBtnClick:(UIButton *)sender {
	// 状态条的方向旋转的方向,来判断当前屏幕的方向
	UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
	// 在cell上并且是竖屏时候响应关闭事件
	if (self.isCellVideo && orientation == UIInterfaceOrientationPortrait) {
		if ([self.delegate respondsToSelector:@selector(zf_controlView:closeAction:)]) {
			[self.delegate zf_controlView:self closeAction:sender];
		}
	} else {
		if ([self.delegate respondsToSelector:@selector(zf_controlView:backAction:)]) {
			[self.delegate zf_controlView:self backAction:sender];
		}
	}
}

- (void)lockScrrenBtnClick:(UIButton *)sender {
	sender.selected = !sender.selected;
	self.showing = NO;
	[self zf_playerShowControlView];
	if ([self.delegate respondsToSelector:@selector(zf_controlView:lockScreenAction:)]) {
		[self.delegate zf_controlView:self lockScreenAction:sender];
	}
}

- (void)playBtnClick:(UIButton *)sender {
	sender.selected = !sender.selected;
	if ([self.delegate respondsToSelector:@selector(zf_controlView:playAction:)]) {
		[self.delegate zf_controlView:self playAction:sender];
	}
}

- (void)closeBtnClick:(UIButton *)sender {
	if ([self.delegate respondsToSelector:@selector(zf_controlView:closeAction:)]) {
		[self.delegate zf_controlView:self closeAction:sender];
	}
}

- (void)fullScreenBtnClick:(UIButton *)sender {
	sender.selected = !sender.selected;
	if ([self.delegate respondsToSelector:@selector(zf_controlView:fullScreenAction:)]) {
		[self.delegate zf_controlView:self fullScreenAction:sender];
	}
}

- (void)repeatBtnClick:(UIButton *)sender {
	// 重置控制层View
	[self zf_playerResetControlView];
	[self zf_playerShowControlView];
	if ([self.delegate respondsToSelector:@selector(zf_controlView:repeatPlayAction:)]) {
		[self.delegate zf_controlView:self repeatPlayAction:sender];
	}
}

- (void)downloadBtnClick:(UIButton *)sender {
	if ([self.delegate respondsToSelector:@selector(zf_controlView:downloadVideoAction:)]) {
		[self.delegate zf_controlView:self downloadVideoAction:sender];
	}
}

- (void)resolutionBtnClick:(UIButton *)sender {
	sender.selected = !sender.selected;
	// 显示隐藏分辨率View
	self.resolutionView.hidden = !sender.isSelected;
}

- (void)centerPlayBtnClick:(UIButton *)sender {
	sender.selected = !sender.selected;
	if ([self.delegate respondsToSelector:@selector(zf_controlView:cneterPlayAction:)]) {
		[self.delegate zf_controlView:self cneterPlayAction:sender];
	}
}

- (void)failBtnClick:(UIButton *)sender {
	self.errorView.hidden = YES;
	if ([self.delegate respondsToSelector:@selector(zf_controlView:failAction:)]) {
		[self.delegate zf_controlView:self failAction:sender];
	}
}

- (void)progressSliderTouchBegan:(ASValueTrackingSlider *)sender {
	[self zf_playerCancelAutoFadeOutControlView];
	self.videoSlider.popUpView.hidden = YES;
	if ([self.delegate respondsToSelector:@selector(zf_controlView:progressSliderTouchBegan:)]) {
		[self.delegate zf_controlView:self progressSliderTouchBegan:sender];
	}
}

- (void)progressSliderValueChanged:(ASValueTrackingSlider *)sender {
	if ([self.delegate respondsToSelector:@selector(zf_controlView:progressSliderValueChanged:)]) {
		[self.delegate zf_controlView:self progressSliderValueChanged:sender];
	}
}

- (void)progressSliderTouchEnded:(ASValueTrackingSlider *)sender {
	self.showing = YES;
	if ([self.delegate respondsToSelector:@selector(zf_controlView:progressSliderTouchEnded:)]) {
		[self.delegate zf_controlView:self progressSliderTouchEnded:sender];
	}
}

/**
 *  应用退到后台
 */
- (void)appDidEnterBackground {
	[self zf_playerCancelAutoFadeOutControlView];
}

/**
 *  应用进入前台
 */
- (void)appDidEnterPlayground {
	if (!self.isShrink) { [self zf_playerShowControlView]; }
}

- (void)playerPlayDidEnd {
	self.backgroundColor  = RGBA(0, 0, 0, .6);
	self.repeatBtn.hidden = NO;
	// 初始化显示controlView为YES
	self.showing = NO;
	// 延迟隐藏controlView
	[self zf_playerShowControlView];
}

/**
 *  屏幕方向发生变化会调用这里
 */
- (void)onDeviceOrientationChange {
	if (ZFPlayerShared.isLockScreen) { return; }
//	self.lockBtn.hidden         = !self.isFullScreen;
	self.fullScreenBtn.selected = self.isFullScreen;
	UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
	if (orientation == UIDeviceOrientationFaceUp || orientation == UIDeviceOrientationFaceDown || orientation == UIDeviceOrientationUnknown || orientation == UIDeviceOrientationPortraitUpsideDown) {
		return;
	}
	if (!self.isShrink && !self.isPlayEnd && !self.showing) {
		// 显示、隐藏控制层
		[self zf_playerShowOrHideControlView];
	}
}

- (void)setOrientationLandscapeConstraint {
	if (self.isCellVideo) {
		self.shrink             = NO;
	}
	self.fullScreen             = YES;
//	self.lockBtn.hidden         = !self.isFullScreen;
	self.fullScreenBtn.selected = self.isFullScreen;
	self.playeBtn.hidden = self.isFullScreen;
	[self makeFullScreenTopView];
	[self makeFullScreenBootomView];
}
/**
 *  设置竖屏的约束
 */
- (void)setOrientationPortraitConstraint {
	self.fullScreen             = NO;
//	self.lockBtn.hidden         = !self.isFullScreen;
	self.fullScreenBtn.selected = self.isFullScreen;
	self.playeBtn.hidden = self.isFullScreen;
	
	[self makeSmallScreenTopView];
	[self makeSmallScreenBootomView];
}

#pragma mark - Private Method

- (void)showControlView {
	self.showing = YES;
	if (self.lockBtn.isSelected) {
		self.topImageView.alpha    = 0;
		self.bottomImageView.alpha = 0;
	} else {
		self.topImageView.alpha    = 1;
		self.bottomImageView.alpha = 1;
	}
	self.backgroundColor           = RGBA(0, 0, 0, 0.3);
	self.lockBtn.alpha             = 1;
	if (self.isCellVideo) {
		self.shrink                = NO;
	}
	self.playeBtn.alpha = self.isFullScreen ? 0 : 1;
	self.playeBtn.hidden = self.isFullScreen;
	self.bottomProgressView.alpha  = 0;
	ZFPlayerShared.isStatusBarHidden = NO;
}

- (void)hideControlView {
	self.showing = NO;
	self.backgroundColor          = RGBA(0, 0, 0, 0);
	self.topImageView.alpha       = self.playeEnd;
	self.bottomImageView.alpha    = 0;
	self.lockBtn.alpha            = 0;
	self.bottomProgressView.alpha = 1;
	self.playeBtn.hidden = YES;
	self.playeBtn.alpha = 0;
	// 隐藏resolutionView
	self.resolutionBtn.selected = YES;
	[self resolutionBtnClick:self.resolutionBtn];
	if (self.isFullScreen && !self.playeEnd && !self.isShrink) {
		ZFPlayerShared.isStatusBarHidden = YES;
	}
}

/**
 *  监听设备旋转通知
 */
- (void)listeningRotating {
	[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
	[[NSNotificationCenter defaultCenter] addObserver:self
						 selector:@selector(onDeviceOrientationChange)
						     name:UIDeviceOrientationDidChangeNotification
						   object:nil];
}


- (void)autoFadeOutControlView {
	[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(zf_playerHideControlView) object:nil];
	[self performSelector:@selector(zf_playerHideControlView) withObject:nil afterDelay:ZFPlayerAnimationTimeInterval];
}

/**
 slider滑块的bounds
 */
- (CGRect)thumbRect {
	return [self.videoSlider thumbRectForBounds:self.videoSlider.bounds
					  trackRect:[self.videoSlider trackRectForBounds:self.videoSlider.bounds]
					      value:self.videoSlider.value];
}

#pragma mark - setter

- (void)setShrink:(BOOL)shrink {
	_shrink = shrink;
	self.closeBtn.hidden = !shrink;
	self.bottomProgressView.hidden = shrink;
}

- (void)setFullScreen:(BOOL)fullScreen {
	_fullScreen = fullScreen;
	self.errorView.fullScreen = fullScreen;
	ZFPlayerShared.isLandscape = fullScreen;
}


#pragma mark - getter

- (UILabel *)titleLabel {
	if (!_titleLabel) {
		_titleLabel = [[UILabel alloc] init];
		_titleLabel.textColor = [UIColor whiteColor];
		_titleLabel.font = [UIFont boldSystemFontOfSize:17.0];
		_titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
	}
	return _titleLabel;
}

- (UIButton *)backBtn {
	if (!_backBtn) {
		_backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
		[_backBtn setImage:ZFPlayerImage(@"ZFPlayer_back_full") forState:UIControlStateNormal];
		[_backBtn addTarget:self action:@selector(backBtnClick:) forControlEvents:UIControlEventTouchUpInside];
	}
	return _backBtn;
}

- (UIImageView *)topImageView {
	if (!_topImageView) {
		_topImageView                        = [[UIImageView alloc] init];
		_topImageView.userInteractionEnabled = YES;
		_topImageView.alpha                  = 0;
		_topImageView.image                  = ZFPlayerImage(@"ZFPlayer_top_shadow");
	}
	return _topImageView;
}

- (UIImageView *)bottomImageView {
	if (!_bottomImageView) {
		_bottomImageView                        = [[UIImageView alloc] init];
		_bottomImageView.userInteractionEnabled = YES;
		_bottomImageView.alpha                  = 0;
		_bottomImageView.image                  = ZFPlayerImage(@"ZFPlayer_bottom_shadow");
	}
	return _bottomImageView;
}

- (UIButton *)lockBtn {
	if (!_lockBtn) {
		_lockBtn = [UIButton buttonWithType:UIButtonTypeCustom];
		[_lockBtn setImage:ZFPlayerImage(@"ZFPlayer_unlock_nor") forState:UIControlStateNormal];
		[_lockBtn setImage:ZFPlayerImage(@"ZFPlayer_lock_nor") forState:UIControlStateSelected];
		[_lockBtn addTarget:self action:@selector(lockScrrenBtnClick:) forControlEvents:UIControlEventTouchUpInside];
		
	}
	return _lockBtn;
}

- (UIButton *)startBtn {
	if (!_startBtn) {
		_startBtn = [UIButton buttonWithType:UIButtonTypeCustom];
		[_startBtn setImage:ZFPlayerImage(@"ZFPlayer_play") forState:UIControlStateNormal];
		[_startBtn setImage:ZFPlayerImage(@"ZFPlayer_pause") forState:UIControlStateSelected];
		[_startBtn addTarget:self action:@selector(playBtnClick:) forControlEvents:UIControlEventTouchUpInside];
	}
	return _startBtn;
}

- (UIButton *)closeBtn {
	if (!_closeBtn) {
		_closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
		[_closeBtn setImage:ZFPlayerImage(@"ZFPlayer_close") forState:UIControlStateNormal];
		[_closeBtn addTarget:self action:@selector(closeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
		_closeBtn.hidden = YES;
	}
	return _closeBtn;
}

- (UILabel *)currentTimeLabel {
	if (!_currentTimeLabel) {
		_currentTimeLabel               = [[UILabel alloc] init];
		_currentTimeLabel.textColor     = [UIColor whiteColor];
		_currentTimeLabel.font          = [UIFont systemFontOfSize:13.0f];
		_currentTimeLabel.textAlignment = NSTextAlignmentCenter;
	}
	return _currentTimeLabel;
}

- (UIProgressView *)progressView {
	if (!_progressView) {
		_progressView                   = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
//		_progressView.progressTintColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.4];
		_progressView.progressImage =  ZFPlayerImage(@"slider_buffer_tracker");
		_progressView.trackImage    = ZFPlayerImage(@"slider_max_tracker");
	}
	return _progressView;
}

- (ASValueTrackingSlider *)videoSlider {
	if (!_videoSlider) {
		_videoSlider                       = [[ASValueTrackingSlider alloc] init];
		_videoSlider.popUpViewCornerRadius = 0.0;
		_videoSlider.popUpViewColor = RGBA(19, 19, 9, 1);
		_videoSlider.popUpViewArrowLength = 8;
		
		[_videoSlider setThumbImage:ZFPlayerImage(@"ZFPlayer_slider") forState:UIControlStateNormal];
		
		_videoSlider.maximumValue          = 1;
		[_videoSlider setMinimumTrackImage:ZFPlayerImage(@"slider_min_tracker") forState:(UIControlStateNormal)];
		[_videoSlider setMaximumTrackImage:ZFPlayerImage(@"slider_max_tracker") forState:(UIControlStateNormal)];
		
		// slider开始滑动事件
		[_videoSlider addTarget:self action:@selector(progressSliderTouchBegan:) forControlEvents:UIControlEventTouchDown];
		// slider滑动中事件
		[_videoSlider addTarget:self action:@selector(progressSliderValueChanged:) forControlEvents:UIControlEventValueChanged];
		// slider结束滑动事件
		[_videoSlider addTarget:self action:@selector(progressSliderTouchEnded:) forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchCancel | UIControlEventTouchUpOutside];
		
		UITapGestureRecognizer *sliderTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapSliderAction:)];
		[_videoSlider addGestureRecognizer:sliderTap];
		
		UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panRecognizer:)];
		panRecognizer.delegate = self;
		[panRecognizer setMaximumNumberOfTouches:1];
		[panRecognizer setDelaysTouchesBegan:YES];
		[panRecognizer setDelaysTouchesEnded:YES];
		[panRecognizer setCancelsTouchesInView:YES];
		[_videoSlider addGestureRecognizer:panRecognizer];
	}
	return _videoSlider;
}

- (UILabel *)totalTimeLabel {
	if (!_totalTimeLabel) {
		_totalTimeLabel               = [[UILabel alloc] init];
		_totalTimeLabel.textColor     = [UIColor whiteColor];
		_totalTimeLabel.font          = [UIFont systemFontOfSize:13.0f];
		_totalTimeLabel.textAlignment = NSTextAlignmentCenter;
	}
	return _totalTimeLabel;
}

- (UIButton *)fullScreenBtn {
	if (!_fullScreenBtn) {
		_fullScreenBtn = [UIButton buttonWithType:UIButtonTypeCustom];
		[_fullScreenBtn setImage:ZFPlayerImage(@"ZFPlayer_fullscreen") forState:UIControlStateNormal];
		[_fullScreenBtn setImage:ZFPlayerImage(@"ZFPlayer_shrinkscreen") forState:UIControlStateSelected];
		[_fullScreenBtn addTarget:self action:@selector(fullScreenBtnClick:) forControlEvents:UIControlEventTouchUpInside];
	}
	return _fullScreenBtn;
}

- (MMMaterialDesignSpinner *)activity {
	if (!_activity) {
		_activity = [[MMMaterialDesignSpinner alloc] init];
		_activity.lineWidth = 1;
		_activity.duration  = 1;
		_activity.tintColor = [[UIColor whiteColor] colorWithAlphaComponent:0.9];
	}
	return _activity;
}

- (UIButton *)repeatBtn {
	if (!_repeatBtn) {
		_repeatBtn = [UIButton buttonWithType:UIButtonTypeCustom];
		[_repeatBtn setImage:ZFPlayerImage(@"ZFPlayer_repeat_video") forState:UIControlStateNormal];
		[_repeatBtn addTarget:self action:@selector(repeatBtnClick:) forControlEvents:UIControlEventTouchUpInside];
	}
	return _repeatBtn;
}

- (UIButton *)downLoadBtn {
	if (!_downLoadBtn) {
		_downLoadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
		[_downLoadBtn setImage:ZFPlayerImage(@"ZFPlayer_download") forState:UIControlStateNormal];
		[_downLoadBtn setImage:ZFPlayerImage(@"ZFPlayer_not_download") forState:UIControlStateDisabled];
		[_downLoadBtn addTarget:self action:@selector(downloadBtnClick:) forControlEvents:UIControlEventTouchUpInside];
	}
	return _downLoadBtn;
}

- (UIButton *)resolutionBtn {
	if (!_resolutionBtn) {
		_resolutionBtn = [UIButton buttonWithType:UIButtonTypeCustom];
		_resolutionBtn.titleLabel.font = [UIFont systemFontOfSize:12];
		_resolutionBtn.backgroundColor = RGBA(0, 0, 0, 0.7);
		[_resolutionBtn addTarget:self action:@selector(resolutionBtnClick:) forControlEvents:UIControlEventTouchUpInside];
	}
	return _resolutionBtn;
}

- (UIButton *)playeBtn {
	if (!_playeBtn) {
		_playeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
		[_playeBtn setImage:ZFPlayerImage(@"ZFPlayer_play_btn_play") forState:UIControlStateNormal];
		[_playeBtn setImage:ZFPlayerImage(@"ZFPlayer_play_btn_paused") forState:UIControlStateSelected];
		[_playeBtn addTarget:self action:@selector(centerPlayBtnClick:) forControlEvents:UIControlEventTouchUpInside];
	}
	return _playeBtn;
}
- (ZFPlayerErrorView *)errorView
{
	if (_errorView == nil) {
		_errorView = [[ZFPlayerErrorView alloc] init];
		__weak __typeof(self)weakSelf = self;
		[_errorView setHandleClickSureCallBack:^{
			__strong __typeof(weakSelf)strongSelf = weakSelf;
			if (strongSelf.fullScreen) {
				[strongSelf backBtnClick:strongSelf.backBtn];
			} else {
				[strongSelf failBtnClick:nil];
			}
		}];
	}
	return _errorView;
}


- (UIView *)fastView {
	if (!_fastView) {
		_fastView                     = [[UIView alloc] init];
		_fastView.backgroundColor     = RGBA(0, 0, 0, 0.8);
		_fastView.layer.cornerRadius  = 4;
		_fastView.layer.masksToBounds = YES;
	}
	return _fastView;
}

- (UIImageView *)fastImageView {
	if (!_fastImageView) {
		_fastImageView = [[UIImageView alloc] init];
	}
	return _fastImageView;
}

- (UILabel *)fastTimeLabel {
	if (!_fastTimeLabel) {
		_fastTimeLabel               = [[UILabel alloc] init];
		_fastTimeLabel.textColor     = [UIColor whiteColor];
		_fastTimeLabel.textAlignment = NSTextAlignmentCenter;
		_fastTimeLabel.font          = [UIFont systemFontOfSize:14.0];
	}
	return _fastTimeLabel;
}

- (UIProgressView *)fastProgressView {
	if (!_fastProgressView) {
		_fastProgressView                   = [[UIProgressView alloc] init];
		_fastProgressView.progressTintColor = DMUIColorFromRGB(0x48dbff);
		_fastProgressView.trackTintColor    = [UIColor colorWithWhite:0 alpha:0.4];
	}
	return _fastProgressView;
}

- (UIImageView *)placeholderImageView {
	if (!_placeholderImageView) {
		_placeholderImageView = [[UIImageView alloc] init];
		_placeholderImageView.userInteractionEnabled = YES;
	}
	return _placeholderImageView;
}

- (UIProgressView *)bottomProgressView {
	if (!_bottomProgressView) {
		_bottomProgressView                   = [[UIProgressView alloc] init];
		_bottomProgressView.progressTintColor = DMUIColorFromRGB(0x48dbff);
		_bottomProgressView.trackTintColor    = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.4];
	}
	return _bottomProgressView;
}
- (ZFContinuePlayView *)continuePlayView
{
	if (_continuePlayView == nil) {
		_continuePlayView = [ZFContinuePlayView continuePlayView];
		__weak __typeof(self)weakSelf = self;
		__weak __typeof(_continuePlayView)weakContinuePlayView = _continuePlayView;
		[_continuePlayView setHandleContinueCallBack:^{
			__strong __typeof(weakSelf)strongSelf = weakSelf;
			__strong __typeof(weakContinuePlayView)strongContinuePlayView = weakContinuePlayView;
			[strongSelf playBtnClick:strongSelf.playeBtn];
			strongContinuePlayView.hidden = YES;
		}];
	}
	return _continuePlayView;
}
- (NSString *)getMinutesSecondsWithStamp:(NSInteger)seconds
{
	NSString *format_time = [NSString stringWithFormat:@"%02d′%02d″",(int)(seconds/60),(int)(seconds%60)];
	return format_time;
}
- (ZFPlayerNetWorkReachability *)reachability
{
	if (_reachability == nil) {
		_reachability = [ZFPlayerNetWorkReachability reachabilityForInternetConnection];
	}
	return _reachability;
}

/// MARK: - BRBarrageRenderer
- (BRBarrageRenderer *)barrageRender
{
	if (_barrageRender == nil) {
		BRBarrageRenderer *renderer = [[BRBarrageRenderer alloc] init];
		renderer.view.backgroundColor = [UIColor clearColor];
		renderer.redisplay = YES;
		renderer.delegate = self;
		renderer.masked   = NO;
		renderer.view.userInteractionEnabled = YES;
		renderer.canvasMargin = UIEdgeInsetsMake(20, 0, DMKSMALL_BOTTONHEIGHT, 0);
		_barrageRender = renderer;
	}
	return _barrageRender;
}
- (NSTimeInterval)timeForBarrageRenderer:(BRBarrageRenderer *)renderer
{
	return self.currentPlayTime;
}
- (UIButton *)barrageSwitchBtn
{
	if (_barrageSwitchBtn == nil) {
		_barrageSwitchBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
		_barrageSwitchBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
		[_barrageSwitchBtn setImage:ZFPlayerImage(@"player_barrage_open") forState:(UIControlStateNormal)];
		[_barrageSwitchBtn setImage:ZFPlayerImage(@"player_barrage_close") forState:(UIControlStateSelected)];
		[_barrageSwitchBtn addTarget:self action:@selector(barrageSwitchBtnClick:) forControlEvents:(UIControlEventTouchUpInside)];
	}
	return _barrageSwitchBtn;
}
- (void)barrageSwitchBtnClick:(UIButton *)button
{
	button.selected = !button.isSelected;
	self.barrageRender.view.hidden = button.isSelected;
}
- (UIButton *)barrageSendBtn
{
	if (_barrageSendBtn == nil) {
		_barrageSendBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
		[_barrageSendBtn setImage:ZFPlayerImage(@"player_btn_send") forState:(UIControlStateNormal)];
		[_barrageSendBtn setImage:ZFPlayerImage(@"player_btn_send") forState:(UIControlStateSelected)];
		[_barrageSendBtn addTarget:self action:@selector(barrageSendBtnClick:) forControlEvents:(UIControlEventTouchUpInside)];
	}
	return _barrageSendBtn;
}
- (void)barrageSendBtnClick:(UIButton *)button
{
	if (self.delegate && [self.delegate respondsToSelector:@selector(zf_controlView:clickSendBarrage:)]) {
		[self.delegate zf_controlView:self clickSendBarrage:button];
	}
}

#pragma mark - UIGestureRecognizerDelegate

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
	CGRect rect = [self thumbRect];
	CGPoint point = [touch locationInView:self.videoSlider];
	if ([touch.view isKindOfClass:[UISlider class]]) { // 如果在滑块上点击就不响应pan手势
		if (point.x <= rect.origin.x + rect.size.width && point.x >= rect.origin.x) { return NO; }
	}
	return YES;
}

#pragma mark - Public method

/** 重置ControlView */
- (void)zf_playerResetControlView {
	[self.activity stopAnimating];
	self.videoSlider.value           = 0;
	self.bottomProgressView.progress = 0;
	self.progressView.progress       = 0;
	self.currentTimeLabel.text       = @"00:00";
	self.totalTimeLabel.text         = @"00:00";
	self.fastView.hidden             = YES;
	self.repeatBtn.hidden            = YES;
	self.playeBtn.hidden             = YES;
	self.resolutionView.hidden       = YES;
	self.errorView.hidden              = YES;
	self.backgroundColor             = [UIColor clearColor];
	self.downLoadBtn.enabled         = YES;
	self.shrink                      = NO;
	self.showing                     = NO;
	self.playeEnd                    = NO;
//	self.lockBtn.hidden              = !self.isFullScreen;
	self.playeBtn.hidden 		= self.isFullScreen;
	self.errorView.hidden              = YES;
	self.continuePlayView.hidden = YES;
	self.placeholderImageView.alpha  = 1;
	__weak __typeof(self)weakSelf = self;
	[self.reachability startNotifier:^(ZFPlayerNetWorkStatus status, ZFPlayerNetWorkReachability *reach) {
		__strong __typeof(weakSelf)strongSelf = weakSelf;
		
		if (status == ZFPlayerNetWorkStatusWWAN2G || status == ZFPlayerNetWorkStatusWWAN3G || status == ZFPlayerNetWorkStatusWWAN4G) {
			/// 暂停播放
			if (strongSelf.playeBtn.isSelected) {
				[strongSelf playBtnClick:strongSelf.playeBtn];
			}
			strongSelf.continuePlayView.hidden = NO;
			
		} else if (status == ZFPlayerNetWorkStatusWiFi) {
			[strongSelf playBtnClick:strongSelf.playeBtn];
			strongSelf.continuePlayView.hidden = YES;
		}
	}];
	[self hideControlView];
}

- (void)zf_playerResetControlViewForResolution {
	self.fastView.hidden        = YES;
	self.repeatBtn.hidden       = YES;
	self.resolutionView.hidden  = YES;
	self.playeBtn.hidden        = YES;
	self.downLoadBtn.enabled    = YES;
	self.errorView.hidden         = YES;
	self.backgroundColor        = [UIColor clearColor];
	self.shrink                 = NO;
	self.showing                = NO;
	self.playeEnd               = NO;
	self.playeBtn.hidden 		= self.isFullScreen;
}

/**
 *  取消延时隐藏controlView的方法
 */
- (void)zf_playerCancelAutoFadeOutControlView {
	[NSObject cancelPreviousPerformRequestsWithTarget:self];
}

/** 设置播放模型 */
- (void)zf_playerModel:(ZFPlayerModel *)playerModel {
	
	// 重置弹幕
	[self.barrageRender reStart];
	
	if (playerModel.title) { self.titleLabel.text = playerModel.title; }
	// 设置网络占位图片
	if (playerModel.placeholderImageURLString) {
		[self.placeholderImageView setImageWithURLString:playerModel.placeholderImageURLString placeholder:ZFPlayerImage(@"ZFPlayer_loading_bgView")];
	} else {
		self.placeholderImageView.image = playerModel.placeholderImage;
	}
	if (playerModel.resolutionDic) {
		[self zf_playerResolutionArray:[playerModel.resolutionDic allKeys]];
	}
	__weak __typeof(self)weakSelf = self;
	if (playerModel.loadBarranges) {
		playerModel.loadBarranges(playerModel, ^(NSArray<DMBarrageData *> *barrages) {
			__strong __typeof(weakSelf)strongSelf = weakSelf;
			NSMutableArray *tmp = [NSMutableArray arrayWithCapacity:barrages.count];
			[barrages enumerateObjectsUsingBlock:^(DMBarrageData * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
				[tmp addObject:obj.descriptor];
			}];
			[strongSelf.barrageRender load:tmp];
		});
	}
	
}

/** 正在播放（隐藏placeholderImageView） */
- (void)zf_playerItemPlaying {
	[UIView animateWithDuration:1.0 animations:^{
		self.placeholderImageView.alpha = 0;
	}];
}

- (void)zf_playerShowOrHideControlView {
	if (self.isShowing) {
		[self zf_playerHideControlView];
	} else {
		[self zf_playerShowControlView];
	}
}
/**
 *  显示控制层
 */
- (void)zf_playerShowControlView {
	if ([self.delegate respondsToSelector:@selector(zf_controlViewWillShow:isFullscreen:)]) {
		[self.delegate zf_controlViewWillShow:self isFullscreen:self.isFullScreen];
	}
	[self zf_playerCancelAutoFadeOutControlView];
	[UIView animateWithDuration:ZFPlayerControlBarAutoFadeOutTimeInterval animations:^{
		[self showControlView];
	} completion:^(BOOL finished) {
		self.showing = YES;
		[self autoFadeOutControlView];
	}];
}

/**
 *  隐藏控制层
 */
- (void)zf_playerHideControlView {
	if ([self.delegate respondsToSelector:@selector(zf_controlViewWillHidden:isFullscreen:)]) {
		[self.delegate zf_controlViewWillHidden:self isFullscreen:self.isFullScreen];
	}
	[self zf_playerCancelAutoFadeOutControlView];
	[UIView animateWithDuration:ZFPlayerControlBarAutoFadeOutTimeInterval animations:^{
		[self hideControlView];
	} completion:^(BOOL finished) {
		self.showing = NO;
	}];
}

/** 小屏播放 */
- (void)zf_playerBottomShrinkPlay {
	self.shrink = YES;
	[self hideControlView];
}

/** 在cell播放 */
- (void)zf_playerCellPlay {
	self.cellVideo = YES;
	self.shrink    = NO;
	[self.backBtn setImage:ZFPlayerImage(@"ZFPlayer_close") forState:UIControlStateNormal];
}

- (void)zf_playerCurrentTime:(NSInteger)currentTime totalTime:(NSInteger)totalTime sliderValue:(CGFloat)value {
	// 当前时长进度progress
	NSInteger proMin = currentTime / 60;//当前秒
	NSInteger proSec = currentTime % 60;//当前分钟
					    // duration 总时长
	NSInteger durMin = totalTime / 60;//总秒
	NSInteger durSec = totalTime % 60;//总分钟
	self.continuePlayView.videoDuration = [self getMinutesSecondsWithStamp:totalTime];
	if (!self.isDragged) {
		self.currentPlayTime = currentTime;
		// 更新slider
		self.videoSlider.value           = value;
		self.bottomProgressView.progress = value;
		// 更新当前播放时间
		self.currentTimeLabel.text       = [NSString stringWithFormat:@"%02zd:%02zd", proMin, proSec];
	}
	
	// 更新总时间
	self.totalTimeLabel.text = [NSString stringWithFormat:@"%02zd:%02zd", durMin, durSec];
}

- (void)zf_playerDraggedTime:(NSInteger)draggedTime totalTime:(NSInteger)totalTime isForward:(BOOL)forawrd hasPreview:(BOOL)preview {
	// 快进快退时候停止菊花
	[self.activity stopAnimating];
	// 拖拽的时长
	NSInteger proMin = draggedTime / 60;//当前秒
	NSInteger proSec = draggedTime % 60;//当前分钟
	
	//duration 总时长
	NSInteger durMin = totalTime / 60;//总秒
	NSInteger durSec = totalTime % 60;//总分钟
	
	NSString *currentTimeStr = [NSString stringWithFormat:@"%02zd:%02zd", proMin, proSec];
	NSString *totalTimeStr   = [NSString stringWithFormat:@"%02zd:%02zd", durMin, durSec];
	CGFloat  draggedValue    = (CGFloat)draggedTime/(CGFloat)totalTime;
	NSString *timeStr        = [NSString stringWithFormat:@"%@ / %@", currentTimeStr, totalTimeStr];
	self.continuePlayView.videoDuration = [self getMinutesSecondsWithStamp:totalTime];
	self.currentPlayTime = draggedTime;
	[self.barrageRender reDisplay];
	// 显示、隐藏预览窗
	self.videoSlider.popUpView.hidden = !preview;
	// 更新slider的值
	self.videoSlider.value            = draggedValue;
	// 更新bottomProgressView的值
	self.bottomProgressView.progress  = draggedValue;
	// 更新当前时间
	self.currentTimeLabel.text        = currentTimeStr;
	// 正在拖动控制播放进度
	self.dragged = YES;
	
	if (forawrd) {
		self.fastImageView.image = ZFPlayerImage(@"ZFPlayer_fast_forward");
	} else {
		self.fastImageView.image = ZFPlayerImage(@"ZFPlayer_fast_backward");
	}
	self.fastView.hidden           = preview;
	self.fastTimeLabel.text        = timeStr;
	self.fastProgressView.progress = draggedValue;
	
}

- (void)zf_playerDraggedEnd {
	dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
		self.fastView.hidden = YES;
	});
	self.dragged = NO;
	// 结束滑动时候把开始播放按钮改为播放状态
	self.startBtn.selected = YES;
	self.playeBtn.selected = YES;
	// 滑动结束延时隐藏controlView
	[self autoFadeOutControlView];
}

- (void)zf_playerDraggedTime:(NSInteger)draggedTime sliderImage:(UIImage *)image; {
	self.currentPlayTime = draggedTime;
	[self.barrageRender reDisplay];
	// 拖拽的时长
	NSInteger proMin = draggedTime / 60;//当前秒
	NSInteger proSec = draggedTime % 60;//当前分钟
	NSString *currentTimeStr = [NSString stringWithFormat:@"%02zd:%02zd", proMin, proSec];
	[self.videoSlider setImage:image];
	[self.videoSlider setText:currentTimeStr];
	self.fastView.hidden = YES;
}

/** progress显示缓冲进度 */
- (void)zf_playerSetProgress:(CGFloat)progress {
	[self.progressView setProgress:progress animated:NO];
}

/** 视频加载失败 */
- (void)zf_playerItemStatusFailed:(NSError *)error {
	self.errorView.hidden = NO;
	[self.barrageRender stop];
}

/** 加载的菊花 */
- (void)zf_playerActivity:(BOOL)animated {
	if (animated) {
		[self.activity startAnimating];
		self.fastView.hidden = YES;
	} else {
		[self.activity stopAnimating];
	}
}

/** 播放完了 */
- (void)zf_playerPlayEnd {
	self.repeatBtn.hidden = NO;
	self.playeEnd         = YES;
	self.showing          = NO;
	// 隐藏controlView
	[self hideControlView];
	self.backgroundColor  = RGBA(0, 0, 0, .3);
	ZFPlayerShared.isStatusBarHidden = NO;
	self.bottomProgressView.alpha = 0;
}

/**
 是否有下载功能
 */
- (void)zf_playerHasDownloadFunction:(BOOL)sender {
	self.downLoadBtn.hidden = !sender;
}

/**
 是否有切换分辨率功能
 */
- (void)zf_playerResolutionArray:(NSArray *)resolutionArray {
	self.resolutionBtn.hidden = NO;
	
	_resolutionArray = resolutionArray;
	[_resolutionBtn setTitle:resolutionArray.firstObject forState:UIControlStateNormal];
	// 添加分辨率按钮和分辨率下拉列表
	self.resolutionView = [[UIView alloc] init];
	self.resolutionView.hidden = YES;
	self.resolutionView.backgroundColor = RGBA(0, 0, 0, 0.7);
	[self addSubview:self.resolutionView];
	
	[self.resolutionView mas_makeConstraints:^(MASConstraintMaker *make) {
		make.width.mas_equalTo(40);
		make.height.mas_equalTo(25*resolutionArray.count);
		make.leading.equalTo(self.resolutionBtn.mas_leading).offset(0);
		make.top.equalTo(self.resolutionBtn.mas_bottom).offset(0);
	}];
	
	// 分辨率View上边的Btn
	for (NSInteger i = 0 ; i < resolutionArray.count; i++) {
		UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
		btn.layer.borderColor = [UIColor whiteColor].CGColor;
		btn.layer.borderWidth = 0.5;
		btn.tag = 200+i;
		btn.frame = CGRectMake(0, 25*i, 40, 25);
		btn.titleLabel.font = [UIFont systemFontOfSize:12];
		[btn setTitle:resolutionArray[i] forState:UIControlStateNormal];
		if (i == 0) {
			self.resoultionCurrentBtn = btn;
			btn.selected = YES;
			btn.backgroundColor = RGBA(86, 143, 232, 1);
		}
		[self.resolutionView addSubview:btn];
		[btn addTarget:self action:@selector(changeResolution:) forControlEvents:UIControlEventTouchUpInside];
	}
}

/** 播放按钮状态 */
- (void)zf_playerPlayBtnState:(BOOL)state {
	
	if (state) {
		[self.barrageRender start];
	} else {
		[self.barrageRender pause];
	}
	
	self.startBtn.selected = state;
	self.playeBtn.selected = state;
}

/** 锁定屏幕方向按钮状态 */
- (void)zf_playerLockBtnState:(BOOL)state {
	self.lockBtn.selected = state;
}

/** 下载按钮状态 */
- (void)zf_playerDownloadBtnState:(BOOL)state {
	self.downLoadBtn.enabled = state;
}
- (void)zf_showBarrangeView:(BOOL)show
{
	self.barrageRender.view.hidden = !show;
}
-(void)zf_receiveBarrangeData:(DMBarrageData *)data
{
	[self.barrageRender receive:data.descriptor];
}

#pragma clang diagnostic pop

@end
